<template>
    <div class="table">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-date"></i>{{$route.name}}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="handle-box">
          <el-dialog :title="title" :visible.sync="dialogFormAddVisible">
            <el-form :model="addOptions" :rules="subRules" ref="addForm">
                <el-form-item label="题目标题" :label-width="formLabelWidth" prop="name">
                    <el-input type="text" v-model="addOptions.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="题目类型" :label-width="formLabelWidth" prop="qTypeId">
                  <el-select v-model="addOptions.qTypeId" placeholder="请选择">
                      <el-option
                          v-for="item in types"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id">
                      </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="是否必填" :label-width="formLabelWidth" prop="isAnswerRequired">
                  <el-select v-model="addOptions.isAnswerRequired" placeholder="请选择">
                      <el-option
                          v-for="item in requireds"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                      </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="题目序号" :label-width="formLabelWidth" prop="orderNumber">
                  <el-input type="number" v-model="addOptions.orderNumber" auto-complete="off">
                  </el-input>
                </el-form-item>
                <el-form-item label="题目选项" :label-width="formLabelWidth">
                  <div class="options" v-model="addOptions.options" v-for="(item, index) in options" :key="index">
                    <el-input type="text" v-model="item.content" auto-complete="off">
                    </el-input>
                    <el-button type="text" size="small" @click="deleSubject(index)">删除</el-button>
                  </div>
                  <el-button type="text" size="small" @click="addSubject()">
                    添加
                  </el-button>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormAddVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitSubject">确 定</el-button>
            </div>
          </el-dialog>
        </div>
        <div>
          <el-table :data="dataSource" border fit style="width: 100%">
                <el-table-column prop="name" label="题目标题" show-overflow-tooltip></el-table-column>
                <el-table-column prop="qTypeId" label="题目类型" show-overflow-tooltip :formatter="typeFor">
                </el-table-column>
                <el-table-column prop="isAnswerRequired" label="是否必填" show-overflow-tooltip :formatter="reFor">
                </el-table-column>
                <el-table-column prop="orderNumber" label="题目序号" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="optionList" label="题目选项" show-overflow-tooltip :formatter="optionFor">
                </el-table-column>
                <!-- <el-table-column prop="state" label="状态" show-overflow-tooltip empty-text :formatter="stateFormatter">
                </el-table-column> -->
                <el-table-column fixed="right" label="操作">
                    <template slot-scope="scope">
                        <!-- <el-button type="text" size="small" @click="edit(scope.row)">编辑</el-button> -->
                        <el-button type="text" size="small" @click="delNotice(scope.row)">删除</el-button>
                        <!-- <el-switch
                            v-model="scope.row.state === 1 ? true : false" 
                            active-color="#13ce66"
                            @change="switchChange(scope.row)"
                        >
                        </el-switch> -->
                    </template>
                </el-table-column>
          </el-table>
          <div class="block">
            <el-pagination
              layout="total, prev, pager, next, jumper" :total="dataSource.length">
            </el-pagination>
          </div>
        </div>
    </div>
</template>
<script>
import { questionnaire } from "../../server/getDate.js";
import { mapState, mapActions } from 'vuex'
const { listQuestionSubjectAllApi, listTypeAllApi,
deleteSubjectApi } = questionnaire
export default {
    data() {
        return {
            dialogFormAddVisible: false,
            title: '',
            addOptions: {},
            formLabelWidth: '120px',
            searchKey: '',
            subRules: {
                name: [{ required: true, message: '请输入题目', trigger: 'blur' }],
                qTypeId: [{ required: true, message: '请选择题目类型', trigger: 'blur' }],
                isAnswerRequired: [{ required: true, message: '请选择是否必填', trigger: 'blur' }],
                orderNumber: [{ required: true, message: '请输入题目序号', trigger: 'blur' }]
            },
            requireds: [{
              value: 1,
              label: '是'
            }, {
              value: 0,
              label: '否'
            }],
            currentId: '',
            options: [],
            codes: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
            'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 
            'U', 'V', 'W', 'X', 'Y', 'Z'],
        }
    },
    created() {
      console.log(this.$route)
      this.currentId = this.$route.query.id
      this.allList()
      this.getTypes()
    },
    computed: mapState({
        dataSource: state => state.Questionnaire.subjectList,
        types: state => state.Questionnaire.typeList
    }),
    methods: {
        ...mapActions(['saveSubjectList', 'saveTypes']),
        allList() {
            listQuestionSubjectAllApi({ qId: this.currentId }).then(res => {
                if (res.code === '000000') {
                    this.saveSubjectList(res)
                } else {
                    this.$message.error(res.message)
                }
            }, err => this.$message.error(err.message) )
        },
        getTypes() {
          listTypeAllApi().then(res => {
            if (res.code === '000000') {
              this.saveTypes(res)
            } else {
              this.$message.error(res.message)
            }
          }, () => {
            this.$message.error('网络错误')
          })
        },
        edit(row) {
            this.dialogFormVisible = true
            this.title = '修改类型'
            this.addForm = {
              id: row.id,
              names: row.name
            }
        },
        deleSubject() {

        },
        addSubject() {

        },
        submitSubject() {

        },
        handleCurrentChange(val) {
            this.allType(val)
        },
        stateFormatter(row) {
            const state = row.state
            return state === 1 ? '启用' : '禁用'
        },
        reFor(row) {
          if (!row.isAnswerRequired) {
            return ''
          } else {
            return row.isAnswerRequired === 1 ? '必填' : '不必填'
          }
        },
        typeFor(row) {
          if (row.qTypeId) {
            let type = ''
            this.types.some(item => {
              if (row.qTypeId === item.id) {
                type = item.name
                return true
              }
            })
            return type
          } else {
            return ''
          }
        },
        optionFor(row) {
          if (row.optionList.length === 0) {
            return '无'
          }
          const datas = []
          row.optionList.forEach(item => {
            datas.push(`${item.code || ''} : ${item.name || ''}`)
          })
          return datas.join('\n')
        },
        delNotice(row) {
            this.$confirm('此操作将永久删除该名称, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteSubjectApi({ ids: row.id }).then(res => {
                    if (res.code === '000000') {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.allList()
                    } else {
                        this.$message.error(res.message)
                    }   
                }, err => this.$message.error(err.message))
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        add(){
            this.$refs['addForm'].validate(valid => {
                if (valid) {
                    if (this.addForm.id) {
                        this.updateType() 
                    } else {
                        this.addAction()
                    }
                }
            })
        },
        addAction() {
            this.dialogFormVisible = false
            addTypeApi({ ...this.addForm }).then(res => {
                if (res.code === '000000') {
                    this.$message.success('添加成功')
                    this.allType(this.page.number)
                } else {
                    this.$message.error(res.message)
                }
            }, err => this.$message.error(err.message))
        },
        updateType() {
            this.dialogFormVisible = false
            const params = {
              id: this.addForm.id,
              name: this.addForm.names
            }
            updateTypeApi({ ...params }).then(res => {
                if (res.code === '000000') {
                    this.$message.success('修改成功')
                    this.allType(this.page.number)
                } else {
                    this.$message.error(res.message)
                }
            }, err => this.$message.error(err.message))
        },
        addType(){
            this.dialogFormVisible = true
            this.title = '新增类型'
            this.addForm = {}
        },
        switchChange(row) {
          disableTypeApi({
            ids: row.id, 
            state: row.state ? '0' : '1' 
          }).then(res => {
            if (res.code === '000000') {
              this.$message.success('修改成功')
              this.allType(this.page.number)
            } else {
              this.$message.error(res.message)
            }
          }, () => {
            this.$message.error('网络错误')
          })
        }
    }
}
</script>
<style lang="scss" scoped>
.handle-box {
  margin-bottom: 1%;
  .search {
    width: 30%;
  }
}

.block {
  text-align: center;
  margin-top: 1%;
}
</style>
